/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nc.kyiv.yellow.sociallibrary.controller.web;

import com.nc.kyiv.yellow.sociallibrary.beans.bookinfo.BookInfoBeanLocal;
import com.nc.kyiv.yellow.sociallibrary.beans.bookinfo.BookInfoBeanLocalHome;
import com.nc.kyiv.yellow.sociallibrary.beans.user.UserBeanLocal;
import com.nc.kyiv.yellow.sociallibrary.beans.user.UserBeanLocalHome;
import com.nc.kyiv.yellow.sociallibrary.dao.LibUser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.CreateException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Controller extends HttpServlet {

    public String formFullUserJSON(String userName, String pass, String firstName,
            String secondName, String socialID, String email, String registrationDate) {

        String JSON;
        JSON = "{ "
                + " \"userName\" : \"" + userName + "\", "
                + " \"pass\" : \"" + pass + "\", "
                + " \"firstName\" : \"" + firstName + "\", "
                + " \"secondName\" : \"" + secondName + "\", "
                + " \"socialID\" : \"" + socialID + "\", "
                + " \"email\" : \"" + email + "\", "
                + " \"registrationDate\" : \"" + registrationDate + "\""
                + "}";
        return JSON;
    }
    /* BookInfo*/
    private BookInfoBeanLocal bookInfoBean = null;

    public void init() throws ServletException {
        super.init();
        bookInfoBean = lookupBookInfoBeanLocal();
        userBean = lookupUserBeanLocal();  // not here
    }
    /**/
    /*
     * UserLogin
     */
    private UserBeanLocal userBean = null;
    String name;
    String pass;
    LibUser user;

    public Map getUserInfoByLogAndPass(String name, String pass) {
        Map user = new HashMap<String, String>();
        user.put("login", name);
        user.put("pass", pass);
        Map backMap = userBean.getUserByLoginAndPass(user);
        return backMap;
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        HttpSession session = request.getSession();

        try {

            switch (request.getParameter("type")) {
                case "onload":
                    out.println("test gonna right");
                    String sessionLogin = (String) session.getAttribute("userLogin");
                    out.println("Session: " + session);

                    if (sessionLogin == null) {
                        /*check if cookies exist*/
                        out.println("No session login. Checking cookies...");

                        String userLogin = "sllogin";
                        String userPass = "slpass";

                        Cookie cookies[] = request.getCookies();
                        Cookie userLoginCookie = null;
                        Cookie userPassCookie = null;

                        if (cookies != null) {
                            for (int i = 0; i < cookies.length; i++) {
                                if (cookies[i].getName().equals(userLogin)) {
                                    userLoginCookie = cookies[i];
                                }
                                if (cookies[i].getName().equals(userPass)) {
                                    userPassCookie = cookies[i];
                                }
                            }
                        }

                        if (userLoginCookie != null) {
                            out.println("Fing coockies! Checking if user exist in DB...");

                            Map checkcoockies = getUserInfoByLogAndPass(userLoginCookie.getValue().toString(), userPassCookie.getValue().toString());

                            if (checkcoockies != null) {
                                /*create new cookies*/
                                Cookie cookieLog = new Cookie("sllogin", userLoginCookie.getValue().toString());
                                cookieLog.setMaxAge(14 * 24 * 60 * 60);
                                Cookie cookiePas = new Cookie("slpass", userPassCookie.getValue().toString());
                                cookiePas.setMaxAge(14 * 24 * 60 * 60);

                                response.addCookie(cookieLog);
                                response.addCookie(cookiePas);
                                /*create a new session*/
                                session.setAttribute("userLogin", checkcoockies.get("login"));
                                session.setAttribute("userPassword", checkcoockies.get("password"));
                                session.setAttribute("userFirstName", checkcoockies.get("firstName"));
                                session.setAttribute("userId", checkcoockies.get("id").toString());
                                session.setAttribute("userRole", checkcoockies.get("role").toString());
                                out.print("Session created");
                            } else {
                                out.print("No in DB detected ... Need to delete this coockies");
                                /*delete bad cookies*/
                                Cookie cookieLog = new Cookie("sllogin", "badCoockies");
                                cookieLog.setMaxAge(0);
                                Cookie cookiePas = new Cookie("slpass", "badCoockies");
                                cookiePas.setMaxAge(0);

                                response.addCookie(cookieLog);
                                response.addCookie(cookiePas);
                                /*redirect to guest page*/
                                out.print("Load guest page");
                            }
                        } else {
                            out.println("no coockies found! Guest page");
                            /*replase to guest page*/
                        }
                    } else {
                        /*create cookies*/
                        Cookie cookieLog = new Cookie("sllogin", (String) session.getAttribute("userLogin"));
                        cookieLog.setMaxAge(14 * 24 * 60 * 60);
                        Cookie cookiePas = new Cookie("slpass", (String) session.getAttribute("userPassword"));
                        cookiePas.setMaxAge(14 * 24 * 60 * 60);

                        response.addCookie(cookieLog);
                        response.addCookie(cookiePas);

                        /*load rolePage*/
                        out.println("Login: " + (String) session.getAttribute("userLogin"));
                        out.println("Password: " + (String) session.getAttribute("userPassword"));
                        out.println("FirstName: " + (String) session.getAttribute("userFirstName"));
                        out.println("ID: " + (String) session.getAttribute("userId").toString());
                        out.println("Role: " + (String) session.getAttribute("userRole").toString());
                        out.println("load definite page to this role");
                    }
                    break;
                case "facebook":
                    out.println(formFullUserJSON("Test", "1111", "NewOne", "none", request.getParameter("socialID"), "a@mail.com", "11.12.13"));
                    break;
                case "twitter":
                    out.println(formFullUserJSON("Test", "1111", "NewOne", "none", request.getParameter("socialID"), "a@mail.com", "11.12.13"));
                    break;
                case "vkontakte":
                    response.sendRedirect("VkServlet");
                case "googlePlus":
                    out.println(formFullUserJSON("Test", "1111", "NewOne", "none", request.getParameter("socialID"), "a@mail.com", "11.12.13"));
                    break;

                case "checknotsocial":

                    Map result = getUserInfoByLogAndPass(request.getParameter("userlog"), request.getParameter("userpass"));

                    if (result != null) {
                        out.print(result.get("firstName"));
                        /*create session*/
                        session.setAttribute("userLogin", result.get("login"));
                        session.setAttribute("userPassword", result.get("password"));
                        session.setAttribute("userFirstName", result.get("firstName"));
                        session.setAttribute("userId", result.get("id").toString());
                        session.setAttribute("userRole", result.get("role").toString());
                        
                        /*create cookies*/
                        Cookie cookieLog2 = new Cookie("sllogin", (String) result.get("login"));
                        cookieLog2.setMaxAge(14 * 24 * 60 * 60);
                        Cookie cookiePas2 = new Cookie("slpass", (String) result.get("password"));
                        cookiePas2.setMaxAge(14 * 24 * 60 * 60);

                        response.addCookie(cookieLog2);
                        response.addCookie(cookiePas2);
                    } else {
                        out.print("false");
                    }
                    break;

                case "registration":
                    String notSplit=request.getParameter("parameters");
                    String [] splited=notSplit.split(";");
                    Map paramsRegistration = new HashMap<String, String>();
                    paramsRegistration.put("login", splited[0]);
                    paramsRegistration.put("pass", splited[1]);
                    paramsRegistration.put("last_name", splited[3]);
                    paramsRegistration.put("first_name", splited[2]);
                    paramsRegistration.put("email", splited[4]);
                    userBean.registerUser(paramsRegistration);
                    out.println("You've been sent a confirmation letter! Please, activate your account during 6 months!");
                    break;

                case "addingNewBook":
                    out.println("This book successfully was added with ISBN " + request.getParameter("isbn") + " !");
                    Map params2 = new HashMap<String, String>();
                    
                    params2.put("isbn", request.getParameter("isbn"));
                    //params2.put("genre", request.getParameter("genre"));
                    params2.put("title", request.getParameter("title"));
                    params2.put("description", request.getParameter("description"));
                    params2.put("numberOfPages", request.getParameter("numberOfPages"));
                    params2.put("image", request.getParameter("image"));
                    bookInfoBean.addBookInfo(params2);
                    break;
                default:
                    out.println("Default message!");
            }

        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private BookInfoBeanLocal lookupBookInfoBeanLocal() {
        try {
            Context c = new InitialContext();
            BookInfoBeanLocalHome rv = (BookInfoBeanLocalHome) c.lookup("java:comp/env/BookInfoBean");
            return rv.create();
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        } catch (CreateException ce) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ce);
            throw new RuntimeException(ce);
        }
    }

    private UserBeanLocal lookupUserBeanLocal() {
        try {
            Context c = new InitialContext();
            UserBeanLocalHome rv = (UserBeanLocalHome) c.lookup("java:comp/env/UserBean");
            return rv.create();
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        } catch (CreateException ce) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ce);
            throw new RuntimeException(ce);
        }
    }

    public String getStringFromHTML(URL url) throws IOException {
        String result = "";
        HttpURLConnection conn;
        BufferedReader rd;
        String line;
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        while ((line = rd.readLine()) != null) {
            result += line;
        }
        return result;
    }
}